package com.example.repair_service.controller.user;

import com.example.repair_service.constant.JwtClaimsConstant;
import com.example.repair_service.dto.UserDTO;
import com.example.repair_service.dto.UserLoginDTO;
import com.example.repair_service.entity.UserEntity;
import com.example.repair_service.mapper.UserMapper;
import com.example.repair_service.properties.JwtProperties;
import com.example.repair_service.result.Result;
import com.example.repair_service.service.UserService;
import com.example.repair_service.util.JwtUtil;
import com.example.repair_service.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/login")
@Tag(name = "C端用户登录相关接口")
@Slf4j
public class LoginController {

    @Autowired
    public UserService userService;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public JwtProperties jwtProperties;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        UserEntity user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);


        UserVO userVO =UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .mobile(user.getMobile())
                .token(token)
                .build();

        //记录最后登录时间
        user.setLastLoginAt(LocalDateTime.now());

        userMapper.setLastLoginAt(user);

        return Result.success(userVO);
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody UserDTO userDTO) {
        log.info("用户注册：{}", userDTO);
        userService.register(userDTO);
        return Result.success("注册成功");
    }


}
